from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from . import brand_serializers
from goods.models import Brand
from fdfs_client.client import Fdfs_client
from django.conf import settings
from rest_framework.response import Response


# brand信息
class BrandViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = brand_serializers.BrandViewSetSerializer
    queryset = Brand.objects.all()

    # 1.重写create方法
    def create(self, request, *args, **kwargs):
        # 1.1 获取参数
        logo = request.FILES.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")

        # 1.2检验参数
        if not all([logo, name, first_letter]):
            return Response(status=403)

        # 1.3数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(logo.read())

        # 1.4判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 1.5数据入库图片
        logo_url = ret.get("Remote file_id")
        Brand.objects.create(logo=logo_url, name=name, first_letter=first_letter)

        # 1.6返回响应
        return Response(status=201)

    # 2.重写update方法
    def update(self, request, *args, **kwargs):
        # 2.1获取参数
        logo = request.FILES.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")
        logo_name = self.get_object()

        # 2.2校验参数
        if not all([logo, name, first_letter]):
            return Response(status=403)

        # 2.3数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(logo.read())

        # 2.4判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 2.5数据入库图片
        logo_url = ret.get("Remote file_id")
        Brand.objects.filter(id=logo_name.id).update(logo=logo_url, name=name, first_letter=first_letter)

        # 2.6返回响应
        return Response(status=201)